#pragma once

#include "SocketException.h"
#include "Socket.h"
#include "Thread.h"

class ISocketListener abstract
{
public:
	virtual void onClientConnected(Socket* client) = 0;
};

class ListenServer : public Thread
{
	Socket mSocket;
	ISocketListener* mEventListener;
public:
	ListenServer(uint16 port, const std::string& bindAddr) : mEventListener(nullptr) {
		mSocket.bind(port, bindAddr);
		mSocket.listen();
	}

	void setEventListener(ISocketListener* listener) {
		mEventListener = listener;
	}

	bool run() {
		while(mState != Thread::ShouldQuit) {
			if(mState == Thread::ShouldPause) {
				Sleep(20);
				continue;
			}

			try {
				Socket* client = mSocket.acceptSocket();
				if(mEventListener != NULL)
					mEventListener->onClientConnected(client);
				else {
					// no one here to handle the connection. Well... so lets close it.
					client->disconnect();
					delete client;
				}
			} catch (SocketException& ) {
				break;
			}
			Sleep(10);
		}

		return true;
	}

	void terminate() {
		mSocket.disconnect();
	}
};